﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.Web;
using Cielo.API.XML;

namespace Cielo.API
{
    internal class WebServiceWrapper
    {
        public RespostaRequisicao EnviarRequisicao(String postData, string cieloGatewayURL)
        {
            var encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes("mensagem=" + postData);

            var sendRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(cieloGatewayURL);
            sendRequest.Method = "POST";
            sendRequest.ContentType = "application/x-www-form-urlencoded";
            sendRequest.ContentLength = data.Length;
            System.IO.Stream sendStream = sendRequest.GetRequestStream();
            sendStream.Write(data, 0, data.Length);
            sendStream.Close();

            System.Net.WebResponse response = sendRequest.GetResponse();
            System.IO.Stream responseStream = response.GetResponseStream();
            System.Text.Encoding responseEnconding = System.Text.Encoding.Default;
            System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream, responseEnconding);
            Char[] charBuffer = new Char[256];
            int count = responseReader.Read(charBuffer, 0, charBuffer.Length);
            StringBuilder result = new StringBuilder();
            while (count > 0)
            {
                result.Append(new String(charBuffer, 0, count));
                count = responseReader.Read(charBuffer, 0, charBuffer.Length);
            }

            return ConversorResultadoGatewayXML.Parse(result.ToString());
        }

    }

}
